<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const arr = [
            { id: 1, text: '1' },
            { id: 2, text: '2' },
            { id: 3, text: '3', parentId: 1 },
            { id: 4, text: '4', parentId: 6 },
            { id: 5, text: '5' },
            { id: 6, text: '6', parentId: 3 }
        ]

        const traverse = (arr) => {
            const res = []
            const copyArr = JSON.parse(JSON.stringify(arr))
            for (let i = 0; i < copyArr.length; i++) {
                if (copyArr[i].parentId === undefined) {
                    res.push(copyArr[i])
                }
            }
            for (let i = 0; i < copyArr.length; i++) {
                if (copyArr[i].parentId !== undefined) {
                    const obj = copyArr.find(e => e.id === copyArr[i].parentId)
                    if (obj) {
                        if (obj.children) {
                            obj.children.push(copyArr[i])
                        } else {
                            obj.children = [copyArr[i]]
                        }
                        delete copyArr[i].parentId
                    }
                }
            }
            return res
        }

        console.log(traverse(arr))
        console.log(arr)
    </script>


</body>

</html>